package com.atguigu.gmall.index.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.core.bean.Resp;
import com.atguigu.gmall.index.annotation.GmallCache;
import com.atguigu.gmall.index.feign.GmallPmsToIndexFeign;
import com.atguigu.gmall.index.service.IndexService;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private GmallPmsToIndexFeign gmallPmsToIndexFeign;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 缓存redis的前缀
     */
    private static final String CATEGORY_CACHE_KEY_PREFIX = "index:cates:";


    /**
     * 查询商品一级分类
     * @return
     */
    @Override
    public List<CategoryEntity> queryLevel1Category() {

        Resp<List<CategoryEntity>> listResp = gmallPmsToIndexFeign.queryCategory(1, null);

        return listResp.getData();
    }

    /**
     * 通过一级分类id查询二级分类及其子类
     * @param pid
     * @return
     */
    @GmallCache(prefix = CATEGORY_CACHE_KEY_PREFIX)
    @Override
    public List<CategoryEntity> querySubCategories(Long pid) {

/*        //查询缓存是否有数据
        String cache = redisTemplate.opsForValue().get(CATEGORY_CACHE_KEY_PREFIX + pid);
        if (StringUtils.isNotBlank(cache)) {
            //将json字符串转为需要的集合
            List<CategoryEntity> categoryEntityList = JSON.parseArray(cache, CategoryEntity.class);
            return categoryEntityList;
        }*/
        //缓存中无数据，则查询数据库
        Resp<List<CategoryEntity>> listResp = gmallPmsToIndexFeign.querySubCategory(pid);
        List<CategoryEntity> respData = listResp.getData();
/*        //将查询的结果放入缓存中
        redisTemplate.opsForValue().set(CATEGORY_CACHE_KEY_PREFIX + pid,JSON.toJSONString(respData));*/
        return respData;
    }

    /**
     * 分布式锁测试
     */
    @Override
    public void testLock() throws InterruptedException {
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,3, TimeUnit.SECONDS);
        if (lock) {
            String num = redisTemplate.opsForValue().get("num");
            if (StringUtils.isBlank(num)) {
                return;
            }
            int i = Integer.parseInt(num);
            redisTemplate.opsForValue().set("num", String.valueOf(++i));

            // 2. 释放锁 del
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            this.redisTemplate.execute(new DefaultRedisScript<>(script), Arrays.asList("lock"), Arrays.asList(uuid));

        }else {
            Thread.sleep(1000);
            testLock();
        }

    }

    public void testLock2() throws InterruptedException {
        RLock lock = redissonClient.getLock("lock");
        lock.lock();
        String num = redisTemplate.opsForValue().get("num");
        if (StringUtils.isBlank(num)) {
            return;
        }
        int i = Integer.parseInt(num);
        redisTemplate.opsForValue().set("num", String.valueOf(++i));
        lock.unlock();
    }



}
